/*
 * @Author: atao
 * @Date: 2023-11-14 09:41:30
 * @LastEditTime: 2023-12-14 16:54:27
 * @FilePath: \yayun-web000\src\store\index.js
 */
/**
 * 
 */
import { decodeApi, encodeApi } from "@/utils";
import Vue from "vue";

import Vuex from "vuex";

Vue.use(Vuex);

/**vuex必须遵守：全局唯一一个store对象，mutations必须是一个纯函数、state数据永远只读 */
/**创建实例 */
// import { createStore } from "vuex";用别人的插件
// import createPersistedState from "vuex-persistedstate";
// const store = createStore({
//      ...
//     plugins: [createPersistedState()],
// });
const store = new Vuex.Store({
    plugins: [
        function (_store) {
            // console.log(arguments)
            let _cache = sessionStorage.getItem("vuex")
            if (_cache) {
                try {
                    //replaceState 替换vuex状态
                    _cache = JSON.parse(decodeApi(_cache));
                    _store.replaceState(_cache);
                } catch { }
            }
            //subscribe订阅执行操作
            _store.subscribe(function (_, _state) {
                
                sessionStorage.setItem("vuex", encodeApi(JSON.stringify(_state)))
            })
            
        }
        // createPersistedState({
        //     storage: window.sessionStorage,
        // })
    ],
    state: {
        // 定义状态
        token: "",
        userInfo: {},
        userRights:{},
        MenuList:{},
    },
    /**向外暴露数据 */
    getters: {
        /**这里传递的方法，vuex会执行二次加工，所以它可以传递state对象进来 */
        token: function (_state) {
            return _state.token;
        },
        userInfo: _state => _state.userInfo,
        userRights: _state => _state.userRights,
        MenuList: _state => _state.MenuList,
    },

    mutations: {
        // 定义方法，只能是同步方法
        setToken: function (_state, token) {
            _state.token = token;
        },
        setUserInfo: function (_state, userInfo) {
            _state.userInfo = userInfo;

        },
        setUserRights: function (_state, userRights) {
            _state.userRights = userRights;

        },
        setMenuList: function (_state, MenuList) {
            _state.MenuList = MenuList;

        },
        
    }
})

export default store;